#coding: utf-8

import nonebot as nb
from .config import *

def setRepeatKeyword(the_type: str, action: str,
        method: str, keyword: str = '', prob: int = 0, group_id: int = 0) -> bool:
    """
    操作复读概率的函数...

    the_type:   'global' or 'local'

    action:     'set' or 'delete'

    method:     'abs', 'inc' or 'all'

    prob:       an integer from 0 to 100

    keyword:    string

    group_id:   the local group id
    """
    global KeywordsRepeatProb
    try:
        if action == 'delete':
            if the_type == 'global':
                if method in ['abs', 'inc']:
                    KeywordsRepeatProb['all'][method] = {}
                if method == 'all':
                    KeywordsRepeatProb['all'] = {'abs': {}, 'inc': {}}
            if the_type == 'local':
                if method in ['abs', 'inc']:
                    KeywordsRepeatProb[group_id][method] = {}
                if method == 'all':
                    KeywordsRepeatProb[group_id] = {'abs': {}, 'inc': {}}
        if action == 'set':
            if the_type == 'global':
                KeywordsRepeatProb['all'][method][keyword] = prob
            if the_type == 'local':
                KeywordsRepeatProb[group_id][method][keyword] = prob
        return True
    except Exception as e:
        nb.logger.warn(__plugin_name__ + '.setRepeatKeyword: ' + e.__repr__())
        return False

def setGroupProb(the_type: str, prob: int, group_id: int = 0) -> bool:
    """
    操作群复读概率函数

    the_type:   'global' or 'local'

    prob:       an integer from 0 to 100

    group_id:   the group id
    """
    global GroupRepeatProb, DEFAULT_GROUP_PROB
    try:
        if the_type == 'global':
            DEFAULT_GROUP_PROB = prob
            for group in GroupRepeatProb.keys():
                GroupRepeatProb[group] = prob
            return True
        elif the_type == 'local':
            GroupRepeatProb[group_id] = prob
            return True
    except Exception as e:
        nb.logger.warn(__plugin_name__ + '.setGroupProb: ' + e.__repr__())
        return False

def setAdmin(user_id: int, method: str, action: str, group_id: int = 0) -> bool:
    """
    操作群管的函数...

    user_id:    the user id

    group_id:   the group id

    method:     'global' or 'local'

    action:     'set' or 'delete'

    """
    global SUPERUSERS
    try:
        if action == 'set':
            if method == 'global':
                SUPERUSERS['all'].add(user_id)
            elif method == 'local':
                SUPERUSERS[group_id].add(user_id)
            else:
                raise KeyError(method)
        elif action == 'delete':
            if method == 'global':
                SUPERUSERS['all'].remove(user_id)
            elif method == 'local':
                SUPERUSERS[group_id].remove(user_id)
            else:
                raise KeyError(method)
        else:
            raise KeyError(action)
        return True
    except Exception as e:
        nb.logger.warn(__plugin_name__ + '.setAdmin: ' + e.__repr__())
        return False

def listInfo(method: str, the_type: str, group_id: int) -> str:
    """
    列出信息的函数...

    method:     'global' or 'local'

    the_type:   'admins', 'keywords' or 'groups'

    group_id:   the group id
    """
    global KeywordsRepeatProb, SUPERUSERS, GroupRepeatProb
    infoList = []
    keywordsHead = '{info} 的关键词复读概率如下:\n  类型     关键词    复读概率\n===================='
    keywordsFormat = '[{type}]  {keyword}  {prob}'
    adminsHead = '{info} 的群管列表如下:\n     QQ\n=================='
    adminsFormat = '{:10d}'
    adminsEnd = "\n超级管理员: {:10d}\n** end **".format(GODUSER)
    groupHead = '{info} 的复读概率如下:\n    群号     概率\n=================='
    groupFormat = '{:11d} {prob}'
    try:
        if the_type == 'admins':
            if method == 'global':
                infoList.append(adminsHead.format(info="全局"))
                for user_id in list(SUPERUSERS['all']):
                    infoList.append(adminsFormat.format(user_id))
                infoList.append(adminsEnd)
            elif method == 'local':
                infoList.append(adminsHead.format(info='群: {:10d}'.format(group_id)))
                for user_id in list(SUPERUSERS[group_id]):
                    infoList.append(adminsFormat.format(user_id))
                infoList.append(adminsEnd)
            else:
                raise KeyError(method)
        elif the_type == 'keywords':
            if method == 'global':
                infoList.append(keywordsHead.format(info='全局'))
                for types in ['abs', 'inc']:
                    for key in KeywordsRepeatProb['all'][types].keys():
                        prob = KeywordsRepeatProb['all'][types][key]
                        infoList.append(keywordsFormat.format(type=types, keyword=key, prob=prob))
                infoList.append('\n** end **')
            elif method == 'local':
                infoList.append(keywordsHead.format(info='群: {:10d}'.format(group_id)))
                for types in ['abs', 'inc']:
                    for key in KeywordsRepeatProb[group_id][types].keys():
                        prob = KeywordsRepeatProb[group_id][types][key]
                        infoList.append(keywordsFormat.format(type=types, keyword=key, prob=prob))
                infoList.append('\n** end **')
            else:
                raise KeyError(method)
        elif the_type == 'groups':
            if method == 'global':
                infoList.append(groupHead.format(info="所有群"))
                for group in GroupRepeatProb.keys():
                    infoList.append(groupFormat.format(group, prob=GroupRepeatProb[group]))
                infoList.append('\n** end **')
            elif method == 'local':
                infoList.append(groupHead.format(info="群: {}".format(group_id)))
                infoList.append(groupFormat.format(group_id, prob=GroupRepeatProb[group_id]))
                infoList.append('\n** end **')
            else:
                raise KeyError(method)
        else:
            raise KeyError(the_type)
        return '\n'.join(infoList)
    except Exception as e:
        nb.logger.warn(__plugin_name__ + '.listInfo: ' + e.__repr__())
        return ''


def analysisCommand(command: str, group_id: int = 0, user_id: int = 0):
    """
    命令解析函数...

    command:    str

    group_id:   int
    """
    global GODUSER, SPECIAL_GROUP
    commandList = command.replace('#', '').split()
    try:
        if commandList[0].lower() == 'setkey':
            # commandList[0]    - 命令参数
            # commandList[1]    - environ
            # commandList[2]    - type
            # commandList[3:-1] - string
            # commandList[-1]   - int
            result = setRepeatKeyword(commandList[1].lower(), 'set', commandList[2].lower(), 
                        ' '.join(commandList[3:-1]), int(commandList[-1]), group_id)
            return '添加成功!' if result else "添加失败!"
        elif commandList[0].lower() == 'delkey':
            # commandList[0]    - 命令参数
            # commandList[1]    - environ
            # commandList[2]    - type
            # commandList[3:]   - string
            result = setRepeatKeyword(commandList[1].lower(), 'delete', commandList[2].lower(), 
                        ' '.join(commandList[3:]), 0, group_id)
        elif commandList[0].lower() == 'setadmin':
            # commandList[0]    - 命令参数
            # commandList[1]    - environ
            # commandList[2:]   - int
            if user_id != GODUSER:
                return "权限不足!"
            qqInfo = getAtList(' '.join(commandList[2:]))
            judge = True
            for qq in qqInfo:
                result = setAdmin(qq, commandList[1].lower(), 'set', group_id)
                if not result:
                    judge = False
            return "添加成功!" if judge else "添加失败!"
        elif commandList[0].lower() == 'setgroup':
            # commandList[0]    - 命令参数
            # commandList[1]    - environ
            # commandList[2]   - int
            result = setGroupProb(commandList[1].lower(), int(commandList[2]), group_id)
            return "设置成功!" if result else "设置失败!"
        elif commandList[0].lower() == 'deladmin':
            # commandList[0]    - 命令参数
            # commandList[1]    - environ
            # commandList[2:]   - int
            if user_id != GODUSER:
                return "权限不足!"
            qqInfo = getAtList(' '.join(commandList[2:]))
            judge = True
            for qq in qqInfo:
                result = setAdmin(qq, commandList[1].lower(), 'delete', group_id)
                if not result:
                    judge = False
            return "删除成功!" if judge else "删除失败!"
        elif commandList[0].lower() == 'listkey':
            # commandList[0]    - 命令参数
            # commandList[1]    - environ
            return listInfo(commandList[1].lower(), 'keywords', group_id)
        elif commandList[0].lower() == 'listadmin':
            # commandList[0]    - 命令参数
            # commandList[1]    - environ
            return listInfo(commandList[1].lower(), 'admins', group_id)
        elif commandList[0].lower() == 'listgroup':
            # commandList[0]    - 命令参数
            # commandList[1]    - environ
            return listInfo(commandList[1], 'groups', group_id)
        elif commandList[0].lower() == 'delallkey':
            # commandList[0]    - 命令参数
            # commandList[1]    - environ
            result = setRepeatKeyword(commandList[1].lower(), 'del', 'all', 
                        '', int(commandList[-1]), group_id)
            return "删除成功!" if result else "删除失败!"
        elif commandList[0].lower() == 'setexcept':
            # commandList[0]    - 命令参数
            if group_id not in SPECIAL_GROUP:
                SPECIAL_GROUP.append(group_id)
                return "添加成功!"
            else:
                return "重复添加! 已在列表中!"
        elif commandList[0].lower() == 'delexcept':
            # commandList[0]    - 命令参数
            if group_id in SPECIAL_GROUP:
                SPECIAL_GROUP.remove(group_id)
                return "删除成功!"
            else:
                return "删除失败! 列表中未包含本群!"
        else:
            raise KeyError(commandList[0])
    except Exception as e:
        nb.logger.warn(__plugin_name__ + '.analysisCommand: ' + e.__repr__())
        return "处理失败!"

